const request = require('request');
const rp = require('request-promise');
const cheerio = require("cheerio");
const REQUEST_URL = "http://192.168.5.66:7002/browse/keyword/";

const _getReadme = (url) => {
  let opts = {
    method: 'GET',
    uri: url
  };
  return new Promise((resolve, reject) => {
    rp(opts).then(res => {
      let $ = cheerio.load(res),
        isNew = false,
        time = $("#readme p").eq(0).find("code").text();
      if (time) {
        let timeval = 1000 * 60 * 60 * 24 * 3;
        let now = new Date().getTime();
        let times = new Date(time).getTime();
        if (now - times <= timeval) isNew = true;
      }
      const reqDom = {
        status: true,
        data: {
          dirtitle: $(".pack-name").text(),
          title: $("#readme h1").text(),
          desc: $(".pack-description").text(),
          img: $("#readme img").eq(0).attr("src") ? $("#readme img").eq(0).attr("src") : "",
          version: $(".pack-ver img").attr("title"),
          isNew,
        }
      }
      resolve(reqDom);
    }).catch(reject)
  })
}

const getDir = (keyword = '@uupt', type = '0') => {
  const opt = {
    method: 'GET',
    uri: REQUEST_URL + keyword
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(async res => {
      let resultArr = [];
      let asyncArr = [];
      let $ = cheerio.load(res);
      let dom = $("#search .col-12").eq(0).find("ul");
      let len = dom.length;
      for (let i = 0; i < len; i++) {
        let adom = dom.eq(i).find("a").text();
        if (adom.endsWith('-block') && type === '0') continue;
        if (!adom.endsWith('-block') && type === '1') continue;
        let str = "http://192.168.5.66:7002" + dom.eq(i).find("a").attr("href");
        asyncArr.push(_getReadme(str));
      }
      let [...rest] = await Promise.all(asyncArr);
      let allRight = rest.every(item => item.status)
      let data = {
        status: allRight,
      }
      if (allRight) {
        rest.map(item => {
          resultArr.push(item.data);
        })
      }
      data.data = resultArr;
      resolve(data)
    }).catch(reject)
  })
}

const sendDings = (sendData) => {
  const opt = {
    method: 'POST',
    uri: sendData.url,
    body: {
      "msgtype": "markdown",
      "markdown": sendData.markdown,
      "at": sendData.at
    },
    json: true,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(resolve).catch(reject)
  })
}

// 获取会话群人员列表
const chatuserList = (chatid) => {
  const opt = {
    method: 'GET',
    uri: "http://uufe.mit.cn/api/chatuserlist?chatid=" + chatid,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(resolve).catch(reject)
  })
}

// 获取用户信息
const getUserInfo = (code) => {
  const opt = {
    method: 'GET',
    uri: "http://uufe.mit.cn/userfeedback/userinfo?code=" + code
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(resolve).catch(reject)
  })
}

const createChat = (name, owner) => {
  const opt = {
    method: 'GET',
    uri: "http://uufe.mit.cn/api/createchat?name=" + name + "&owner=" + owner,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(resolve).catch(reject)
  })
}

const updateChat = (chatid, name, owner) => {
  const opt = {
    method: 'GET',
    uri: "http://uufe.mit.cn/api/updatechat?chatid=" + chatid + "&name=" + name + "&owner=" + owner,
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }
  return new Promise((resolve, reject) => {
    rp(opt).then(resolve).catch(reject)
  })
}

module.exports = { getDir, sendDings, chatuserList, getUserInfo, createChat, updateChat };